<?php

declare(strict_types=1);

namespace app\common\services;

use app\common\model\User as UserModel;
use app\common\model\StationMessage as StationMessageModel;
use app\common\model\PushMsg as PushMsgModel;
use app\common\controller\Wechatclass;
use think\facade\Cache;

/**
 * @xk 发送信息
 */
class SendMsg
{
    /**
     * @xk 发送验证码
     *
     * @method sendMsg
     * @param  [type]                  $tel                      [description]
     * @param  [type]                  $act                      [description]
     * @return [type]                                            [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-12T13:38:58+080
     */
    public static function sendCode($tel, $act)
    {
        $al_template = config('core_config.ali_msg_config.'.$act.'_template');
        return self::sendMsg($tel, '', $al_template, $act);
    }
    /**
     * @xk 执行发送
     *
     * @method sendMsg
     * @param  string                  $phone                    [description]
     * @param  string                  $templateparam            [description]
     * @param  string                  $al_template              [description]
     * @return [type]                                            [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-12T13:42:19+080
     */
    public static function sendMsg($phone='18678997335', $templateparam='', $al_template='', $act='')
    {
        if (!preg_match("/^1[3456789]{1}\d{9}$/", $phone)) {
            return false;
            exit();
        }
        $al_signname = config('core_config.ali_msg_config.al_signname');
        $code = '';
        if ('' == $templateparam) {
            $code = rand(111111, 999999);
            $templateparam = ['code' => $code];
        }
        $params = [
          'SignName' => $al_signname, //阿里云短信模板
          'Format' => 'JSON',
          'Version' => config('core_config.ali_msg_config.al_version'),
          'RegionId' => 'cn-hangzhou', //短信
          'AccessKeyId' => config('core_config.ali_msg_config.al_access_key'), //阿里云APPID
          'SignatureVersion' => '1.0', //签名算法版本
          'SignatureMethod' => 'HMAC-SHA1', //签名方式
          'SignatureNonce' => uniqid(),
          'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'), //请求时间戳 格式化输出2019-11-13T12:12:12Z
          'Action' => 'SendSms', //API名称
          'TemplateCode' => $al_template,
          'PhoneNumbers' => $phone, //电话
          'TemplateParam' => json_encode($templateparam), //更换为自己的实际模版
        ];
        // 计算签名并把签名结果加入请求参数
        $params['Signature'] = self::makeMsgSign($params, config('core_config.ali_msg_config.al_access_secret'));  //阿里云appscript
        $url = 'http://dysmsapi.aliyuncs.com/?'.http_build_query($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $result = curl_exec($ch);
        curl_close($ch);
        // createLog('sendMsg/', $result);
        $result = json_decode($result, true);
        if ('OK' != $result['Code']) {
            return $result;
        } else {
            if ($code != '') {
                Cache::set('sms_'.$act.'_'.$phone, $code, 300);
            }
            return $result;
        }
    }
    /**
     * @xk 阿里云短信生成签名
     *
     * @method   makeMsgSign
     * @Version： V2.0
     * @Author   xkyinzhe
     * @Time     2021-01-08T11:25:50+080
     * @param    [type]                  $data      [description]
     * @param    [type]                  $al_access [description]
     * @return   [type]                  [description]
     */
    public static function makeMsgSign($data, $al_access)
    {
        ksort($data); //对关联数组按照键名进行升序排序。
      $string = ''; //初始化 生成的请求串
      // 使用&和=将请求数组转化为字符串
      foreach ($data as $key => $value) {
          $string .= '&'.urlencode($key).'='.urlencode($value);
      }
        $stringToSign = 'GET&'.urlencode('/').'&'.urlencode(substr($string, 1)); //根据阿里云规则生成要执行签名的字符串
        $sign = base64_encode(hash_hmac('sha1', $stringToSign, $al_access.'&', true));

        return $sign;
    }
    // *****************************
    // | 执行消息通知推送
    // *******************************
    public static function sendPushMsg($user_sn='', $title='', $content='', $type=0, $push_data=[])
    {
        // 开始获取消息推送通知
        $userModel = new UserModel();
        $pushMsgModel = new PushMsgModel();
        $aliPushMsg = new AliPushMsg();
        $user_info = $userModel
                  ->where([['user_sn','=',$user_sn]])
                  ->field('`user_sn`,`wechat_openId`,`android_device_id`,`ios_device_id`')
                  ->find();
        if ($user_info) {
            $user_info = $user_info->toArray();
            $push_data =array_merge($push_data,$user_info);
            $push_data['title'] = $title;
            $push_data['content'] = $content;
            $push_data['type'] = $type;
            if ($user_info['wechat_openId']) {
                // 存在微信公众号ID  可以进行微信公众号推送
                $push_data['is_wechat'] = self::sendWechatMsg($user_info, $title, $content, $type, $push_data);
                if($push_data['is_wechat'] == 1){
                  $push_data['create_time'] = date('Y-m-d H:i:s');
                }
            }
            if ($user_info['android_device_id']) {
                $push_data['is_android'] = $aliPushMsg->androidSend($user_info['android_device_id'], $title, $content, '');
                if($push_data['is_android'] == 1){
                  $push_data['android_time'] = date('Y-m-d H:i:s');
                }
            }
            if ($user_info['ios_device_id']) {
                $push_data['is_ios'] = $aliPushMsg->iosSend($user_info['ios_device_id'], $title, $content, '');
                if($push_data['is_ios'] == 1){
                  $push_data['ios_time'] = date('Y-m-d H:i:s');
                }
            }
            $pushMsgModel->create($push_data);
        }
    }
    /**
     * @xk 推送微信模板消息
     *
     * @method sendWechatMsg
     * @param  string        $user_sn                   [description]
     * @param  array         $data                      [description]
     * @param  string        $type                      [description]
     * @return [type]        [description]
     * @Time   2021-12-02
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public static function sendWechatMsg($user_info=[], $title='', $content = '', $type='0', $push_data=[])
    {
        // return 1;
        $user_sn = $user_info['user_sn'];
        if ($user_sn != '') {
            $options = [
              'appid' => config('core_config.wechat_config.app_id'), // 填写高级调用功能的app id
              'appsecret' => config('core_config.wechat_config.app_script'), // 填写高级调用功能的密钥
            ];
            $weObj = new Wechatclass($options);
            $data = [];
            $data['touser'] = $user_info['wechat_openId'];
            switch ($type) {
              case '1':
                $data['data']= [
                  'first'=>['value'=>$content,'color'=>''],
                  'keyword1'=>['value'=>$push_data['user_name'],'color'=>''],
                  'keyword2'=>['value'=>$push_data['create_time'] ,'color'=>''],
                  'remark'=>['value'=>'','color'=>'']
                ];//内容主体
                $data['template_id'] = 'D1LSSrR9QeYdkiwAJRnhVhnHzcrWuBAw1mlJmxqltcA';
                $result = $weObj->sendTemplateMessage($data);
                return 1;
                break;
              case '2':
                $data['data']= [
                  'first'=>['value'=>$content,'color'=>''],
                  'keyword1'=>['value'=>$push_data['create_user_sn'],'color'=>''],
                  'keyword2'=>['value'=>$push_data['user_name'] ,'color'=>''],
                  'keyword3'=>['value'=>$push_data['time'] ,'color'=>''],
                  'remark'=>['value'=>'','color'=>'']
                ];//内容主体
                // $data['template_id'] = 'tM4yCi18c2iDy9h6wEEqawwg7zi32hTczOqRJbOsius';
                $data['template_id'] = 'KNZUE4KK5chFsiaMHSn_NCFXnZUQhsYGytCaL1k7cVw';
                $result = $weObj->sendTemplateMessage($data);
                return 1;
                break;
              case '3':
                $data['data']= [
                  'first'=>['value'=>$content,'color'=>''],
                  'keyword1'=>['value'=>$push_data['sub_order_sn'],'color'=>''],
                  'keyword2'=>['value'=>$push_data['company_name'] ,'color'=>''],
                  'keyword3'=>['value'=>$push_data['company_num'] ,'color'=>''],
                  'remark'=>['value'=>'','color'=>'']
                ];//内容主体
                // bMTVieO1pG6ESI_w-RMIh9ZeChxxUujPcJj4_KB0qBo
                $data['template_id'] = 'bMTVieO1pG6ESI_w-RMIh9ZeChxxUujPcJj4_KB0qBo';
                $result = $weObj->sendTemplateMessage($data);

                return 1;
                break;
              case '4':
                $data['data']= [
                  'first'=>['value'=>$content,'color'=>''],
                  'keyword1'=>['value'=>$push_data['sub_order_sn'],'color'=>''],
                  'keyword2'=>['value'=>'￥'.$push_data['total_price'],'color'=>''],
                  'keyword3'=>['value'=>$push_data['company_name'] ,'color'=>''],
                  'keyword4'=>['value'=>$push_data['company_num'] ,'color'=>''],
                  'remark'=>['value'=>'','color'=>'']
                ];//内容主体
                $data['template_id'] = 'iq5Ry2uwJr6v6RrcgiOfKteM34ep1rCa-Hx0eAcFyiw';
                $result = $weObj->sendTemplateMessage($data);
                return 1;
                break;
              case '5':
                $data['data']= [
                  'first'=>['value'=>$content,'color'=>''],
                  'keyword1'=>['value'=>'￥'.$push_data['money'],'color'=>''],
                  'keyword2'=>['value'=>$push_data['time'] ,'color'=>''],
                  'remark'=>['value'=>'','color'=>'']
                ];//内容主体
                $data['template_id'] = 'aTwT7f66KOLpLAVN9IZhqJeslTZLoLDNbk2NmgXCVGY';
                $result = $weObj->sendTemplateMessage($data);
                return 1;
                break;
              case '6':
                $data['data']= [
                  'first'=>['value'=>$content,'color'=>''],
                  'keyword1'=>['value'=>$push_data['user_name'],'color'=>''],
                  'keyword2'=>['value'=>'￥'.$push_data['money'] ,'color'=>''],
                  'remark'=>['value'=>'','color'=>'']
                ];//内容主体
                $data['template_id'] = 'HvpNyvmpetcoKPOnEmxL3_oYz8BJ0535Lp_uTXrACas';
                $result = $weObj->sendTemplateMessage($data);
                return 1;
                break;
              case '7':
                $data['data']= [
                  'first'=>['value'=>$content,'color'=>''],
                  'keyword1'=>['value'=>$push_data['name'],'color'=>''],
                  'keyword2'=>['value'=>$push_data['tel'] ,'color'=>''],
                  'keyword3'=>['value'=>$push_data['refund_order_sn'] ,'color'=>''],
                  'keyword4'=>['value'=>'￥'.$push_data['all_price'] ,'color'=>''],
                  'keyword5'=>['value'=>$push_data['content'] ,'color'=>''],
                  'remark'=>['value'=>'','color'=>'']
                ];//内容主体
                $data['template_id'] = 'jRiXPSuJ0vYgtRE4dYY6oMbCLtnwW5CKgyCjt1sEdA0';
                $result = $weObj->sendTemplateMessage($data);
                return 1;
                break;
              default:
                return 0;
                break;
            }
        }
    }
}
